package main

import (
	
	"github.com/astaxie/beego"
	_ "github.com/lib/pq"
	_ "monitor/routers"
	//"github.com/robfig/cron" //go get XXX 定时模块
	"log"
	"fmt"
	"monitor/monitorcon"
	"monitor/models"
	"strconv"
	"time"
	
	"github.com/astaxie/beego/orm"
    
	//"gopkg.in/redis.v4" //redis
)



func main() {

	log.Println("monitorapp start")

    initDB()
    
    callmonitor()

    //connect rabbitmq 
    err := monitorcon.SetupRMQ("amqp://guest:guest@localhost:5672") // amqp://用户名:密码@地址:端口号/host  
  
    if err != nil {  
        log.Println("err : ", err.Error())  
    }  
 
    monitorcon.Consumemessage(callbackmsg)
    beego.Run()
     
	
	
}

func initDB() {
	orm.RegisterDriver("postgres", orm.DRPostgres) // 注册驱动
	psqlInfo := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%d sslmode=disable", monitorcon.User, monitorcon.Password, monitorcon.Dbname, monitorcon.Host, monitorcon.Port)
	log.Println(psqlInfo)
	orm.RegisterDataBase("default", "postgres", psqlInfo)

	orm.RegisterModel(new(models.Stackinfo))
	orm.RegisterModel(new(models.Portinfo))
	orm.RegisterModel(new(models.Interfaceinfo))
	orm.RegisterModel(new(models.Cpuinfo))
	orm.RegisterModel(new(models.Memoryinfo))
	orm.RegisterModel(new(models.Macinfo))
	log.Println("db is successfull connected!")

   	 
	return
}



func callmonitor(){
    	//for redis client
    maxnum := beego.AppConfig.String("maxconnection")       //得到最大连接数
    imax, err := strconv.Atoi(maxnum)
	if err != nil {
		log.Println(err)
		imax=monitorcon.MAXCONNUM
	}
    
    //生成redismanager
    rsmanager:=new (monitorcon.RedisManager)
	rsmanager.CreateClient()
	rsmanager.SetMaxconnum(imax)
	
	monitorcon.SetrsManager(rsmanager)
	

	
	//生成监控实例
	m := new(monitorcon.InstanceManager)

    //把监控实例付给datamanager
    monitorcon.SetInstanceManager(m)
    
	mid:=m.Init(rsmanager)
    if mid>0 {
	   log.Println("分配的实例有效")
	}
	

	pdtime := beego.AppConfig.String("period") //周期时间，单位秒

		//aChan := make(chan int, 1)
	tt, err := strconv.Atoi(pdtime)
	if err != nil {
		log.Println("period time is not set, deafult time is 5s")
		//panic(err)
		tt = 5
	}

	ticker := time.NewTicker(time.Second * time.Duration(tt))

	go func() {
		for {
			select {
			case <-ticker.C:
				log.Printf("ticked at %v\n", time.Now())
				
				//定时更新
				if mid >0 {
				   m.Updatetoken(rsmanager)
				   
				   //m.Do("123",callbacktest)
				   
				}
			}
		}

	}()
    
}

func callbackmsg(msg string) bool{
   log.Printf(msg)
   log.Printf("get callbackmsg:%s",msg)
   return true
}


func callbacktest(hostuuid string) bool { 
   log.Printf("call back function is invoked,hostuuid=%s",hostuuid)
   
   return true 
}